package com.javaketang.dky.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.javaketang.dky.entity.*;
import com.javaketang.dky.mapper.*;
import com.javaketang.dky.service.impl.EasybuyProductCategoryServiceImpl;
import com.javaketang.dky.service.impl.EasybuyProductServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.plugin.dom.core.Element;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author dky
 * @since 2021-07-06
 */
@Controller
@RequestMapping("user")
public class EasybuyUserController {

    //用户映射属性
    @Resource
    private EasybuyUserMapper easybuyUserMapper;

    //商品类
    @Resource
    private EasybuyProductCategoryMapper categoryMapper;

    //新闻类
    @Resource
    private EasybuyNewsMapper newsMapper;

    //订单类
    @Resource
    private EasybuyOrderDetailMapper detailMapper;

    //商品类
    @Resource
    private EasybuyProductMapper productMapper;

    /**
     * 分类服务层
     */
    @Resource
    private EasybuyProductCategoryServiceImpl categoryService;

    /**
     * 购物车类
     */
    @Resource
    private ShoppingCarMapper carMapper;

    /**
     * 用户类
     */
    @Resource
    private EasybuyUserMapper userMapper;

    /**
     * 登陆页面
     *
     * @return
     */
    @RequestMapping("/login")
    public String login() {

        return "Login";
    }

    /**
     * 判断是否登陆成功
     *
     * @param loginName
     * @param password
     * @return
     */
    @RequestMapping("/log")
    @ResponseBody
    public Map<String, Object> log(String loginName, String password, Model model, HttpSession session) {

        System.out.println(loginName + "\t" + password);

        //创建map集合
        Map<String, Object> map = new HashMap<>();

        EasybuyUser easybuyUser = easybuyUserMapper.selectOne(new QueryWrapper<EasybuyUser>().eq("loginName", loginName).eq("password", password));

        //判断查询出来的值为空时
        if (easybuyUser != null) {

            map.put("status", 1);
            map.put("message", "登陆成功！");

            //赋值session
            session.setAttribute("userSession", easybuyUser);

        } else {

            map.put("status", 0);
            map.put("message", "登陆失败，用户名或密码错误！");
        }

        return map;
    }

    /**
     * 查询分类
     *
     * @return
     */
    public Map classify(HttpSession session) {
        //获取session
        EasybuyUser userSession = (EasybuyUser) session.getAttribute("userSession");

        List<EasybuyProductCategory> list = categoryMapper.selectList(new QueryWrapper<EasybuyProductCategory>().eq("type", 1));
        List<EasybuyProductCategory> list2 = categoryMapper.selectList(new QueryWrapper<EasybuyProductCategory>().inSql("parentId", "select id from easybuy_product_category where type=1"));
        List<EasybuyProductCategory> list3 = categoryMapper.selectList(new QueryWrapper<EasybuyProductCategory>().inSql("parentId", "select id from easybuy_product_category where type=2"));
        List<EasybuyNews> easybuyNews = newsMapper.selectList(new QueryWrapper<EasybuyNews>().last("limit 0,5"));

        List<ShoppingCar> order = carMapper.selectList(new QueryWrapper<ShoppingCar>().eq("userId", userSession == null ? 0 : userSession.getId()).eq("isDelete", 0));    //查询订单

        //接收一级分类id
        List<Integer> listPid = new ArrayList<>();

        for (EasybuyProductCategory category : list) {

            listPid.add(category.getId());

        }


        //查询主页面
        List list4 = categoryService.queryProductClassify(listPid);

        System.out.println("集合：" + list4.size());

        //创建map集合
        Map<String, Object> map = new HashMap<>();

        map.put("list", list);//分类1
        map.put("list2", list2);//分类2
        map.put("list3", list3);//分类3
        map.put("list4", list4);
        map.put("easybuyNews", easybuyNews);  //新闻
        map.put("order", order);  //购物车

        //保留2为小数点
        DecimalFormat df = new DecimalFormat(".00");

        //总价格
        double sumPrice = 0;

        //循环订单
        for (ShoppingCar news : order) {

            //累加
            sumPrice += news.getSumPrice();
        }

        //保留2位小数点
        sumPrice = Double.parseDouble(df.format(sumPrice));

        //赋值总价格
        map.put("sumPrice", sumPrice);

        //赋值购物车数量
        session.setAttribute("order", order);

        //赋值总价格
        session.setAttribute("sumPrice", sumPrice);


        return map;
    }

    /**
     * 过滤器跳转的方法
     *
     * @return
     */
    @RequestMapping("/initIndex")
    public String initIndex(Model model, HttpSession session) {


        model.addAllAttributes(classify(session));
        return "index";
    }


    /**
     * 注册方法
     *
     * @return
     */
    @RequestMapping("/regist")
    public String regist() {


        return "Regist";
    }

    /**
     * 注册方法
     *
     * @param easybuyUser 用户对象
     * @param pwd         确认密码
     * @param model
     * @return
     */
    @RequestMapping("/registered")
    @ResponseBody
    public Map<String, Object> registered(EasybuyUser easybuyUser, Model model) {

        //创建map集合
        Map<String, Object> map = new HashMap<>();

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("loginName", easybuyUser.getLoginName());

        //查询登陆名
        EasybuyUser easybuyUser1 = easybuyUserMapper.selectOne(wrapper);

        //查询登陆名
        if (easybuyUser1 == null) {

            //添加方法
            int row = easybuyUserMapper.insert(easybuyUser);

            //判断添加成功时
            if (row > 0) {

                map.put("status", "1");
                map.put("message", "注册成功");

                return map;
            }


        } else {

            map.put("status", "0");
            map.put("message", "注册失败，登陆名已存在");

        }


        return map;
    }

    /**
     * 退出方法
     *
     * @return
     */
    @RequestMapping("/loginOut")
    public String loginOut(HttpSession session) {

        //删除session
        session.removeAttribute("userSession");

        return "login";
    }

    /**
     * 后台管理
     *
     * @param id      用户id
     * @param session session
     * @return
     */
    @RequestMapping("/admin")
    public String admin(Integer id, HttpSession session) {

        System.out.println("id--->>>" + id);
        session.setAttribute("action", "");

        return "Member_User";
    }


    /**
     * 点击分类管理
     *
     * @return
     */
    @RequestMapping("/product")
    public String product(Integer current, Integer id, Integer type, Model model, HttpSession session) {

        System.out.println("id-->>" + id + "\t类型--》》" + type);

        model.addAttribute("id", id);
        model.addAttribute("type", type);

        //分页
        Page<EasybuyProductCategory> page = new Page<>(current == null ? 1 : current, 10);

        //查询商品
        List list = categoryService.queryProduct(page, id, type);

        //获取总页数
        int sumDateNumber = (int) (page.getTotal() % 10 == 0 ? page.getTotal() / 10 : page.getTotal() / 10 + 1);
        model.addAttribute("lists", list);
        model.addAttribute("sumPage", sumDateNumber);
        model.addAttribute("current", current == null ? 1 : current);

        model.addAllAttributes(classify(session));

        session.setAttribute("page", "page");

        return "BrandList";
    }

    /**
     * 查询用户列表
     *
     * @return
     */
    @RequestMapping("/memberCollect")
    public String memberCollect(String action, Integer current, HttpSession session, Model model) {

        //判断不为空时
        if (action != null && action != "") {
            //判断是咨询列表
            if (action.equals("memberCollect")) {

                //分页
                Page<EasybuyUser> page = new Page<>(current == null ? 1 : current, 10);

                IPage<EasybuyUser> easybuyNewsIPage = easybuyUserMapper.selectPage(page, null);

                //获取总页数
                int sumDateNumber = (int) (page.getTotal() % 10 == 0 ? page.getTotal() / 10 : page.getTotal() / 10 + 1);

                System.out.println("数据总页数--》》" + sumDateNumber);

                //赋值到集合中
                List<EasybuyUser> list = easybuyNewsIPage.getRecords();

                list.forEach(System.out::println);

                model.addAttribute("lists", list);
                model.addAttribute("sumPage", sumDateNumber);
                model.addAttribute("current", current == null ? 1 : current);

            }
        }

        session.setAttribute("action", "memberCollect");


        return "Member_User";
    }


    /**
     * 添加用户
     *
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/toAddUser")
    public String toAddUser(Integer id, HttpSession session, Model model) {

        session.setAttribute("action", "toAddUser");

        //判断为修改时
        if (id != null) {

            EasybuyUser user = userMapper.selectById(id);

            System.out.println("用户信息---》》》》》=====================" + user);

            model.addAttribute("user", user);

        }

        return "Member_User";
    }

    /**
     * 添加用户
     *
     * @param easybuyUser
     * @return
     */
    @RequestMapping("/addUser")
    @ResponseBody
    public Map<String, Object> addUser(EasybuyUser easybuyUser) {

        //创建map集合
        Map<String, Object> map = new HashMap<>();

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("loginName", easybuyUser.getLoginName());

        //查询登陆名
        EasybuyUser easybuyUser1 = easybuyUserMapper.selectOne(wrapper);

        //查询登陆名
        if (easybuyUser1 == null) {

            //添加方法
            int row = easybuyUserMapper.insert(easybuyUser);

            //判断添加成功时
            if (row > 0) {

                map.put("status", "1");
                map.put("message", "添加成功");

                return map;
            }


        } else {

            map.put("status", "0");
            map.put("message", "添加失败，登陆名已存在");

        }

        return map;
    }

    /**
     * 删除用户
     *
     * @return
     */
    @RequestMapping("/deleteUserById")
    @ResponseBody
    public Map<String, Object> deleteUserById(Integer id) {

        //创建map集合
        Map<String, Object> map = new HashMap<>();

        //删除用户
        int i = userMapper.deleteById(id);

        //判断删除成功
        if (i > 0) {
            map.put("status", 1);
            map.put("message", "删除成功");

        } else {

            map.put("status", 0);
            map.put("message", "删除失败，服务器内部错误");

        }


        return map;
    }

    /**
     * 修改用户
     *
     * @param easybuyUser
     * @return
     */
    @RequestMapping("/updateUser")
    @ResponseBody
    public Map<String, Object> updateUser(EasybuyUser easybuyUser) {

        System.out.println("修改用户对象----》》》" + easybuyUser);

        //创建map集合
        Map<String, Object> map = new HashMap<>();

        //查询登陆名
        int row = easybuyUserMapper.updateById(easybuyUser);

        //判断修改成功时
        if (row > 0) {

            map.put("status", "1");
            map.put("message", "修改成功");

            return map;
        } else {
            map.put("status", "0");
            map.put("message", "修改失败，服务器内部错误！请联系管理员");
        }


        return map;
    }


    /**
     * 搜索
     *
     * @return
     */
    @RequestMapping("/search")
    public String search(Integer current, String name, Model model, HttpSession session) {


        //分页
        Page<EasybuyProduct> page = new Page<>(current == null ? 1 : current, 10);

        //查询商品
        IPage<EasybuyProduct> iPage = productMapper.selectPage(page, new QueryWrapper<EasybuyProduct>().like("name", name));

        //转换为集合
        List<EasybuyProduct> list = iPage.getRecords();


        System.out.println("1：" + iPage.getTotal() + "\t2:" + iPage.getPages() + "\t3:" + iPage.getCurrent() + "\t4:" + iPage.getSize());


        model.addAttribute("lists", list);
        model.addAttribute("sumPage", iPage.getPages());  //
        model.addAttribute("current", current == null ? 1 : current);

        model.addAllAttributes(classify(session));
        model.addAttribute("name", name);
        session.setAttribute("page", "pages");
        model.addAttribute("name", name);//赋值搜索

        return "BrandList";
    }


}

